﻿using System;
using System.Configuration;
using System.IO;
using System.Web;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;

namespace TSharp.Core.Aop
{
    /// <summary>
    /// 配置文件获取
    /// <para>by tangjingbo at 2010-1-8 16:27</para>
    /// </summary>
    public static class WebConfigUtil
    {
        /// <summary>
        /// 获取外部配置文件
        /// </summary>
        /// <param name="appkeyOrFileName">web.config 中AppSettings的key或者配置文件名称</param>
        /// <returns></returns>
        public static FileConfigurationSource Get(string appkeyOrFileName)
        {
            string aopcfg = ConfigurationManager.AppSettings.Get(appkeyOrFileName);
            if (string.IsNullOrEmpty(aopcfg))
            {
                aopcfg = appkeyOrFileName + ".config";
            }
            string cfgfile = null;
            cfgfile = aopcfg.StartsWith("~/")
                          ? HttpContext.Current.Server.MapPath(aopcfg)
                          : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, aopcfg);
            if (File.Exists(cfgfile))
                return new FileConfigurationSource(cfgfile);
            throw new FileNotFoundException(string.Format("‘{0}’配置文件不存在", cfgfile));
        }

        /// <summary>
        /// 
        /// <para>by tangjingbo at 2010-03-19 16:48</para>
        /// </summary>
        /// <typeparam name="TSection">The type of the section.</typeparam>
        /// <param name="appkeyOrFileName">Name of the appkey or file.</param>
        /// <param name="section">The section.</param>
        /// <returns></returns>
        [Obsolete("已过时，不再使用外部配置文件")]
        private static TSection GetSection<TSection>(string appkeyOrFileName, string section)
            where TSection : ConfigurationSection
        {
            return (TSection) Get(appkeyOrFileName).GetSection(section);
        }

        /// <summary>
        /// 获取默认配置文件Selction节点的配置
        /// </summary>
        /// <typeparam name="TSection">The type of the section.</typeparam>
        /// <param name="sectionName">The section.</param>
        /// <returns></returns>
        public static TSection GetSection<TSection>(string sectionName) where TSection : ConfigurationSection
        {
            return ConfigurationManager.GetSection(sectionName) as TSection;
        }
    }
}